import React, { useState, useEffect } from 'react';
import { Button, Uploader, Input, Form } from 'react-vant';
import { useNavigate } from 'react-router-dom'
import { history } from 'umi'
import axios from 'axios';

import { Image, Checkbox } from 'react-vant'
import './index.less'
const Login = () => {
    const [username, usernameState] = useState('') //昵称
    const [phone, phoneState] = useState('')       //手机号
    const [code, codeState] = useState('')          //验证码
    const [count, countState] = useState(0)         //倒计时
    const [sending, setSending] = useState(false)
    const [flag, setflag] = useState(false)
    const [txt, settxt] = useState('')

    // const nav = useNavigate()
    //更新倒计时的时间
    useEffect(() => {
        if (count > 0) {
            setTimeout(() => {
                countState(count - 1)
            }, 1000)
        }
    }, [count])

    //随机生成验证码
    const generateCode = () => {
        const code = Math.floor(Math.random() * 9000 + 1000)
        localStorage.setItem('code1', code)
        return code;
    }
    //发送验证码
    const sendCode = () => {
        if (sending) {
            return;
        }
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(phone)) {
            alert('手机格式不正确')
            return;
        }
        const code = generateCode()
        setTimeout(() => {
            alert(`验证码发送到了${phone}`)
            countState(60)
            setSending(true)
        }, 1000)
        console.log(code);
        settxt(code)
    }

    //绑定
    const handleUsername = (value) => {
        usernameState(value)
    }
    const handlePhone = (value) => {
        phoneState(value)
    }
    const handleCode = (value) => {
        codeState(value)
    }
    //提交
    const handleSubmit = async () => {
        await axios.post("http://localhost:3000/logins", { phone, code }).then(res => {
            console.log(res);
            if (res.data.code == "200") {
                if (localStorage.getItem('code1') == code) {
                    localStorage.setItem('token', res.data.token)
                    localStorage.setItem('login_id', res.data.login._id)
                    alert('登录成功')

                    // nav('/app')
                } else {
                    alert('验证码错误')
                }
                //跳转
                router.push('/app');
            } else if (res.data.code == "202") {
                alert('用户名不存在')
            } else if (res.data.code == "201") {
                alert('手机号错误')
            }
        })
    }
    const [form] = Form.useForm()

    const onFinish = values => {
        console.log(values)
    }

    return (
        <div className="login">
            <div className="biaodan">
                <Image width='100%' height='100%' src="	https://www.axured.cn/assets/axurefiles/dd9eb05e6076c704b2c1e0053def3cc6/images/%E7%99%BB%E5%BD%95/u37.png" />
                {/* <div style={{ position: "relative", top: "-70px", border: "1px solid grey" }}> */}
                <Form
                    form={form}
                    onFinish={onFinish}
                    footer={
                        <div style={{ margin: '16px 16px 0' }}>
                            <Button round nativeType='submit' type='primary' block disabled={flag ? '' : 'disabled'}
                                onClick={() => {
                                    console.log(code);
                                    if (code == txt) {
                                        history.push('/')
                                    } else {
                                        console.log('登录失败')
                                    }
                                }}>
                                登录
                            </Button>
                        </div>
                    }
                >
                    <Form.Item
                        rules={[{ required: true, message: '请填写昵称' }]}
                        name='username'
                    >
                        <Input placeholder='请输入昵称' value={phone} onChange={handleUsername} />
                    </Form.Item>
                    <Form.Item
                        rules={[{ required: true, message: '请填写手机号' }]}
                        name='phoneNumber'
                    >
                        <Input placeholder='请输入手机号' value={phone} onChange={handlePhone} />
                    </Form.Item>

                    <Form.Item
                        rules={[{ required: true, message: '请填写验证码' }]}
                        name='code'
                    >
                        <Input placeholder='请输入验证码' value={code} onChange={handleCode} />
                        <Button disabled={count > 0} onClick={() => {
                            sendCode()
                            console.log();
                        }}>{count > 0 ? `${count}秒后重试` : '发送验证码'}</Button>
                    </Form.Item>

                    <Checkbox defaultChecked shape='square' checked={flag} checkedColor='#85AB52' style={{ height: "15px", width: '15px' }} onChange={(e) => {
                        console.log(e);
                        setflag(e)
                    }}>
                    </Checkbox>
                    <span style={{ display: 'inline-block' }}>我已同意 <span style={{ color: '#93BD0D' }}>用户协议</span></span>
                </Form>
            </div>
        </div>
    );
}

export default Login


